package com.marveal.rabbit.producer.config.database;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@Import(value = {
        RabbitProducerDataSourceProperties.class
        , DataSourceSelector.class
})
public class RabbitProducerDataSourceConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitProducerDataSourceConfiguration.class);

    private final RabbitProducerDataSourceProperties properties;

    private final DataSourceSelector dataSourceSelector;

    public RabbitProducerDataSourceConfiguration(
            RabbitProducerDataSourceProperties rabbitProducerDataSourceProperties,
            DataSourceSelector dataSourceSelector) {
        this.properties = rabbitProducerDataSourceProperties;
        this.dataSourceSelector = dataSourceSelector;
    }

    @Bean(value = "rabbitProducerDataSource")
    @Primary
    public DataSource rabbitProducerDataSource() throws SQLException {
        DataSource rabbitProducerDataSource = DataSourceBuilder
                .create()
                .url(properties.getUrl())
                .username(properties.getUsername())
                .password(properties.getPassword())
                .type(properties.getDataSourceType())
                .driverClassName(properties.getDriverClassName())
                .build();
        DataSource dataSource = null;
        if ("com.zaxxer.hikari.HikariDataSource".equals(properties.getDataSourceType().getName())) {
            dataSource = dataSourceSelector.getHikariDataSource(rabbitProducerDataSource);
        } else {
            dataSource = rabbitProducerDataSource;
        }
		LOGGER.info("============= DataSource : {} ================", JSONUtil.toJsonStr(dataSource));
        return dataSource;
    }

    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    public DataSource primaryDataSource() {
        return primaryDataSourceProperties().initializeDataSourceBuilder().build();
    }

}
